<template>
  <view class="tree-wrapper">
    <view class="header pt-32rpx pb-16rpx">
      <view
        class="main font-size-34rpx font-500 h-44rpx line-height-44rpx mb-16rpx flex justify-center align-center"
      >
        <!-- <text>A组</text> -->
        <text>{{ eventType }}</text>
        <text>淘汰赛</text>
      </view>
      <view
        class="sub font-size-26rpx font-400 h-26rpx line-height-26rpx color-#606266 flex justify-center align-center"
      >
        <text>人队数: {{ playerCount }} 总轮数: {{ groupLoopCount }}</text>
        <!-- <text>轮空: 0</text> -->
      </view>
    </view>
    <view class="body" style="padding: 72rpx 40rpx">
      <view class="tree-detail">
        <block v-for="(row, rowIndex) in tableData" :key="rowIndex">
          <view class="row">
            <block v-for="(colData, colIndex) in row" :key="colIndex">
              <view v-if="colData.col === 0" class="col no-border"></view>
              <view v-if="colData.col === 1" class="col border-full">
                {{ getPlayerDisplayInfo(colData.playerIndex) }}
              </view>
              <view v-if="colData.col === 3" class="col border-right"></view>
              <view v-if="colData.col === 4" class="col border-middle"></view>
              <view v-if="colData.col === 5" class="col border-middle-rb"></view>
              <view v-if="colData.col === 6" class="col border-middle-rt"></view>
            </block>
          </view>
        </block>
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
import { Group, EventToPlayer, Match, Stage, EliminationStage } from '@/championship'
import { EventTypeText } from '@/common/enum'
import { ref } from 'vue'

const props = defineProps<{
  groupInfo: Group
  players: EventToPlayer[]
  stageInfo: Stage
}>()
const playerCount = ref(props.stageInfo.playerCount)
const groupLoopCount = computed(() => {
  let _loopCount = 0
  props.groupInfo.matchInfos.forEach((item) => {
    item.groupLoopIndex > _loopCount && (_loopCount = item.groupLoopIndex)
  })
  return _loopCount
})
const eventType = ref(EventTypeText[props.groupInfo.matchInfos[0].type])
const genTableData = (playerCount: number) => {
  let playerIndex = 0
  const gen3n = (lin3n2) => {
    const row = []
    if (!lin3n2) {
      // 没有上一行数据
      for (let i = 0; i < playerCount * 2 - 1; i++) {
        // row.push(i % 2 === 0 ? 1 : 0)
        if (i % 2 === 0) {
          row.push({ col: 1, playerIndex: playerIndex++ })
        } else {
          row.push({ col: 0 })
        }
      }
    } else {
      lin3n2.forEach((item, index) => {
        if (item.col === 4) {
          // row.push(1)
          row.push({ col: 1, playerIndex: playerIndex++ })
        } else {
          // row.push(0)
          row.push({ col: 0 })
        }
      })
    }
    return row
  }
  // 生成第3n+1行数据， 根据上一行数据，从左到右 奇数位的1 和偶数位的1 进行关联，奇数位的关联数字是6， 偶数位的关联数字是5， 5和6之间用3 相连，在重新生成一下这个数据
  const gen3n1and3n2 = (Lin3n) => {
    // const lastLine = tableData[tableData.length - 1]
    const line3n1 = []
    const line3n2 = new Array(Lin3n.length).fill({ col: 0 })
    let lastLeftPlayerIndex = null
    Lin3n.forEach((item, index) => {
      const last3n1Number = line3n1[index - 1]?.col
      if (item.col === 0) {
        if (!last3n1Number || last3n1Number === 5) {
          // line3n1.push(0)
          line3n1.push({ col: 0 })
        } else {
          // line3n1.push(3)
          line3n1.push({ col: 3 })
        }
      } else if (item.col === 1) {
        if (!last3n1Number || last3n1Number === 0) {
          // line3n1.push(6)
          line3n1.push({ col: 6 })
          lastLeftPlayerIndex = index
        } else if (last3n1Number === 3) {
          // line3n1.push(5)
          line3n1.push({ col: 5 })
          const middlePosition =
            (index - lastLeftPlayerIndex) % 2 === 1
              ? Math.floor(index - lastLeftPlayerIndex / 2) + 1
              : (index - lastLeftPlayerIndex) / 2
          line3n2[lastLeftPlayerIndex + middlePosition] = { col: 4 }
          lastLeftPlayerIndex = null
        }
      }
    })
    return {
      line3n1,
      line3n2,
    }
  }

  const rotateCounterClockwise = (matrix) => {
    if (!matrix || matrix.length === 0 || matrix[0].length === 0) {
      return []
    }

    const rows = matrix.length
    const cols = matrix[0].length
    const rotated = new Array(cols).fill(0).map(() => new Array(rows).fill(0))

    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < cols; j++) {
        rotated[cols - 1 - j][i] = matrix[i][j]
      }
    }

    return rotated
  }
  const tableData = []
  // 填充tableData, index是生成的行号从0开始，如果满足3n的时候调用gen3n, 如果满足3n+1的时候调用gen3n1and3n2,由于gen3n1and3n2会生成两行，所以需要向tableData 中填充两行，while 循环的终止条件是新添加的数据，里边只有一个1
  let isOver = false
  while (!isOver) {
    if (tableData.length % 3 === 0) {
      const lastLine = tableData[tableData.length - 1]
      const line3n = gen3n(lastLine)
      tableData.push(line3n)
    } else if (tableData.length % 3 === 1) {
      const lastLine = tableData[tableData.length - 1]
      const { line3n1, line3n2 } = gen3n1and3n2(lastLine)
      tableData.push(line3n1)
      tableData.push(line3n2)
    }
    // 检查新添加的数据，里边只有一个1
    const lastLine = tableData[tableData.length - 1]
    if (lastLine.filter((item) => item.col === 1).length === 1) {
      isOver = true
    }
  }
  return rotateCounterClockwise(tableData)
}
const getPlayersInOrder = () => {
  const playersInOrder = []
  const matchInfos = props.groupInfo.matchInfos
  const playerMap = {}
  const searchPlayerInfo = (playerInfo) => {
    if (!playerInfo) {
      return null
    }
    playerInfo.team = playerInfo.teamName ? { name: playerInfo.teamName } : null
    playerInfo.player = playerInfo.player1Name ? { name: playerInfo.player1Name } : null
    playerInfo.player2 = playerInfo.player2Name ? { name: playerInfo.player2Name } : null
    return playerInfo
    // if (playerMap[registrationIndex]) {
    //   return playerMap[registrationIndex]
    // } else {
    //   const playerInfo = props.players.find((player) => {
    //     return player.registrationIndex === registrationIndex
    //   })
    //   playerMap[registrationIndex] = playerInfo
    //   return playerInfo
    // }
  }
  const sortedMatchInfos = matchInfos.sort((a, b) => {
    return a.groupMatchIndex - b.groupMatchIndex
  })
  sortedMatchInfos.forEach((matchInfo: Match, index) => {
    const homePlayerInfo = searchPlayerInfo(matchInfo.homePlayer)
    const awayPlayerInfo = searchPlayerInfo(matchInfo.awayPlayer)
    if (homePlayerInfo) {
      // homePlayerInfo.rally = matchInfo.homePlayerRally
      if (matchInfo.groupLoopIndex === 1) {
        homePlayerInfo.basicPlayer = true
      }
    }
    if (awayPlayerInfo) {
      // awayPlayerInfo.rally = matchInfo.awayPlayerRally
      if (matchInfo.groupLoopIndex === 1) {
        awayPlayerInfo.basicPlayer = true
      }
    }
    playersInOrder.push(homePlayerInfo)
    playersInOrder.push(awayPlayerInfo)
    if (matchInfo.rangeMin === 1 && matchInfo.rangeMax === 2) {
      // 最后一场比赛需要把winner 找到
      const winner =
        matchInfo.winnerId === matchInfo.homePlayerId ? matchInfo.homePlayer : matchInfo.awayPlayer
      const winnerPlayerInfo = searchPlayerInfo(winner)
      playersInOrder.push(winnerPlayerInfo)
    }
  })
  return playersInOrder
}
const getPlayerDisplayInfo = (playerIndex) => {
  const playerInfo = playersInOrder[playerIndex]
  let res = ''
  if (playerInfo) {
    res = `${playerInfo?.player?.name || playerInfo?.team?.name || ''} ${playerInfo?.player2Name || ''}`
  }
  return res
}
const playersInOrder = getPlayersInOrder()
const totalPlayerCount =
  props.groupInfo.matchInfos.filter((item) => {
    return item && item.groupLoopIndex === 1
  }).length * 2
const tableData = ref(genTableData(totalPlayerCount))
</script>

<style lang="scss" scoped>
.tree-wrapper {
  // width: 100px;
  // height: 50px;
  background-color: white;
}
.body {
  overflow: scroll;
}
.row {
  display: flex;
  flex-wrap: nowrap;
}
.col {
  position: relative;
  flex-shrink: 0; // 添加这一行来防止宽度压缩
  // width: 50rpx;
  height: 64rpx;
  font-size: 30rpx;
  line-height: 64rpx;
  &:nth-child(3n + 1) {
    width: 180rpx;
    // width: 90rpx;
  }
  &:nth-child(3n + 2) {
    width: 40rpx;
    // width: 20rpx;
  }
  &:nth-child(3n + 3) {
    width: 30rpx;
    // width: 15rpx;
  }
}
.no-border {
  border: none;
}
.border-full {
  overflow: hidden;
  text-align: center;
  background: rgb(236, 245, 255);
  border-radius: 16rpx;
}
.border-right {
  &::before {
    position: absolute;
    top: 0;
    right: 0;
    width: 1px;
    height: 100%;
    content: '';
    background: #3b6eff;
  }
}
.border-middle {
  &::before {
    position: absolute;
    top: 50%;
    left: 0;
    width: 100%;
    height: 1px;
    content: '';
    background: #3b6eff;
  }
}
.border-middle-rb {
  &::before {
    position: absolute;
    top: 50%;
    left: 0;
    width: 100%;
    height: 1px;
    content: '';
    background: #3b6eff;
  }
  &::after {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 1px;
    height: 50%;
    content: '';
    background-color: #3b6eff;
  }
}
.border-middle-rt {
  &::before {
    position: absolute;
    top: 50%;
    left: 0;
    width: 100%;
    height: 1px;
    content: '';
    background: #3b6eff;
  }
  &::after {
    position: absolute;
    top: 0;
    right: 0;
    width: 1px;
    height: 50%;
    content: '';
    background-color: #3b6eff;
  }
}
</style>
